package com.dotlink.appuser.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.QueryParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dotlink.appuser.entity.UserInfo;
import com.dotlink.appuser.service.UserInfoService;
import com.dotlink.frame.filter.WebContext;
import com.dotlink.frame.sms.SMSUtil;
import com.dotlink.frame.utils.Const;
import com.dotlink.frame.utils.Md5;
import com.dotlink.frame.utils.ResponseUtils;
import com.dotlink.frame.utils.StringUtil;
import com.dotlink.frame.utils.ValidatorUtils;
import com.dotlink.frame.utils.redis.RedisCache;

/**
 * APP用户信息
 * 
 * @author liupf
 */
@Controller
@RequestMapping(value = "/api/appuser")
public class UserInfoAPIController {

	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private RedisCache cacheImpl;

	@RequestMapping(value = "/set", method = RequestMethod.GET)
	@ResponseBody
	public Object setCode(@QueryParam("phone") String phone) {
		String authCode = new java.util.Random().nextInt(999999) + "";
		cacheImpl.setEx(phone, authCode, 10);// 存入redis
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("msg", authCode);
		return ResponseUtils.buildSuccessRes(map);
	}

	/**
	 * APP用户登录
	 * 
	 * @author liupf
	 * @param phone
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public Object login() {
		try {
			HttpServletRequest req = WebContext.currentRequest();
			String phone = (String) req.getParameter("phone");
			String password = (String) req.getParameter("password");
			if (StringUtil.isEmpty(phone) || StringUtil.isEmpty(password)) {
				return ResponseUtils.buildErrorRes(Const.GENERAL_ERROR, "参数不全");
			}
			// 保存用户信息
			UserInfo user = new UserInfo();
			user.setPhone(phone);
			UserInfo userinfo = userInfoService.queryUserInfo(user);
			if (userinfo == null) {
				return ResponseUtils.buildErrorRes(Const.GENERAL_ERROR, "该手机号码不存在");
			}
			String md5pwd = Md5.GetMD5Code(password);
			if (!userinfo.getPassword().equals(md5pwd)) {
				return ResponseUtils.buildErrorRes(Const.GENERAL_ERROR, "账号密码不正确");
			}
			// 返回保存结果
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("user", userinfo);
			return ResponseUtils.buildSuccessRes(map);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseUtils.buildErrorRes(Const.GENERAL_ERROR, e.getMessage());
		}
	}

	/**
	 * 获取（注册/修改密码）验证码
	 * 
	 * @param account
	 * @return
	 */
	@RequestMapping(value = "/verify", method = RequestMethod.GET)
	@ResponseBody
	public Object registerVerify(@QueryParam("phone") String phone) {
		// 验证手机号格式是否正确
		boolean isPhone = ValidatorUtils.isMobileNO(phone);
		if (!isPhone) {
			return ResponseUtils.buildErrorRes(Const.GENERAL_ERROR, "请输入正确的手机号码");
		}
		String authCode = new java.util.Random().nextInt(999999) + "";
		String content = "您的验证码是：" + authCode + ",请在10分钟内输入【咔咔兔】";
		boolean result = SMSUtil.sendSMS(phone, content);// 发送短信
		if (result) {
			int time = 60 * 10;// 验证码有效时长
			cacheImpl.setEx(phone, authCode, time);// 存入redis
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("msg", "验证码发送成功");
			return ResponseUtils.buildSuccessRes(map);
		} else {
			return ResponseUtils.buildErrorRes(Const.GENERAL_ERROR, "发送验证码失败");
		}
	}

	/**
	 * 手机注册
	 * 
	 * @param account
	 * @return
	 */
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	@ResponseBody
	public Object register() {
		try {
			HttpServletRequest req = WebContext.currentRequest();
			String phone = (String) req.getParameter("phone");
			String verifycode = (String) req.getParameter("verifycode");
			String password = (String) req.getParameter("password");
			if (StringUtil.isEmpty(phone) || StringUtil.isEmpty(verifycode) || StringUtil.isEmpty(password)) {
				return ResponseUtils.buildErrorRes(Const.GENERAL_ERROR, "参数不全");
			}
			// 从Redis中获取验证码
			String code = cacheImpl.get(phone);
			if (!verifycode.equals(code)) {
				return ResponseUtils.buildErrorRes(Const.GENERAL_ERROR, "验证码不正确");
			}
			// 保存用户信息
			UserInfo user = new UserInfo();
			user.setUsername(phone);
			user.setPhone(phone);
			user.setRole(UserInfo.ROLE_SIMPLE);
			String md5pwd = Md5.GetMD5Code(password);
			user.setPassword(md5pwd);
			UserInfo userinfo = userInfoService.queryUserInfo(user);
			if (userinfo != null) {
				return ResponseUtils.buildErrorRes(Const.GENERAL_ERROR, "该手机号已注册");
			}
			Integer res = userInfoService.saveUser(user);
			// 返回保存结果
			if (res > 0) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("user", phone);
				return ResponseUtils.buildSuccessRes(map);
			} else {
				return ResponseUtils.buildErrorRes(Const.GENERAL_ERROR, "注册失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseUtils.buildErrorRes(Const.GENERAL_ERROR, e.getMessage());
		}
	}

	/**
	 * 修改密码
	 * 
	 * @param account
	 * @return
	 */
	@RequestMapping(value = "/password/update", method = RequestMethod.POST)
	@ResponseBody
	public Object updatePassword() {
		try {
			HttpServletRequest req = WebContext.currentRequest();
			String phone = (String) req.getParameter("phone");
			String verifycode = (String) req.getParameter("verifycode");
			String password = (String) req.getParameter("password");
			if (StringUtil.isEmpty(phone) || StringUtil.isEmpty(verifycode) || StringUtil.isEmpty(password)) {
				return ResponseUtils.buildErrorRes(Const.GENERAL_ERROR, "参数不全");
			}
			// 从Redis中获取验证码
			String code = cacheImpl.get(phone);
			if (!verifycode.equals(code)) {
				return ResponseUtils.buildErrorRes(Const.GENERAL_ERROR, "验证码不正确");
			}
			// 获取用户信息
			UserInfo user = new UserInfo();
			user.setPhone(phone);
			UserInfo userinfo = userInfoService.queryUserInfo(user);
			if (userinfo == null) {
				return ResponseUtils.buildErrorRes(Const.GENERAL_ERROR, "该手机号码不存在");
			}
			// 更新用户密码
			user.setPassword(Md5.GetMD5Code(password));
			Integer res = userInfoService.updateUser(user);
			// 返回保存结果
			if (res > 0) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("user", phone);
				return ResponseUtils.buildSuccessRes(map);
			} else {
				return ResponseUtils.buildErrorRes(Const.GENERAL_ERROR, "注册失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseUtils.buildErrorRes(Const.GENERAL_ERROR, e.getMessage());
		}
	}

}
